package com.mmlc.meimei.lichengkongjian.mine;

import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.been.ContactsList;
import com.mmlc.meimei.lichengkongjian.been.ContactsPerson;
import com.mmlc.utils.ViewUtils;
import com.wang.avi.AVLoadingIndicatorView;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;



public class ActivityContacts extends InterActivity {

    List<ContactsPerson> datas = new ArrayList<>();
    @InjectView(R.id.expand_contacts)
    ExpandableListView expand_contacts;
    @InjectView(R.id.activity_cantacts)
    LinearLayout activity_cantacts;
    @InjectView(R.id.avi)
    AVLoadingIndicatorView avi;
    private ExpandAdapter mAdapter;
    private ContactsList mList;
    SharedPreferences sp;
    //保存文件的路径
    @Override
    protected int initContentView() {
        return R.layout.activity_contacts;
    }
    @Override
    protected void initView() {
        ButterKnife.inject(this);
        ViewUtils.getView(activity, R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initData();
    }

    private void initData() {
        avi.show();
        datas = new ArrayList<>();
        sp = getSharedPreferences("share_data", MODE_PRIVATE);
        if(!TextUtils.isEmpty(sp.getString("contactslist",""))){
            read();
        }else {
            visitContacts();
        }
        expand_contacts.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                String number = datas.get(groupPosition).getContactsNumbers().get(childPosition);
                String name = datas.get(groupPosition).getName();
                Intent intent = new Intent();
                intent.putExtra("name", name);
                intent.putExtra("number", number);
                setResult(RESULT_OK, intent);
                finish();
                return true;
            }
        });
    }


    public class ExpandAdapter extends BaseExpandableListAdapter {
        List<ContactsPerson>  groupInfo ;
        public ExpandAdapter(List<ContactsPerson> data) {
            this.groupInfo = data;
        }

        @Override
        public int getGroupCount() {
            return groupInfo.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return groupInfo.get(groupPosition).getContactsNumbers().size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return groupInfo.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return groupInfo.get(groupPosition).getContactsNumbers().get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            View view = convertView;
            GroupHolder holder = null;
            if (view == null) {
                holder = new GroupHolder();
                view = LayoutInflater.from(ActivityContacts.this).inflate(R.layout.group_name, null);
                holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
                holder.arrow = (ImageView) view.findViewById(R.id.iv_arrow);
                view.setTag(holder);
            } else {
                holder = (GroupHolder) view.getTag();
            }

            //判断是否已经打开列表
            if (isExpanded) {
                holder.arrow.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_down));
            } else {
                holder.arrow.setBackgroundDrawable(getResources().getDrawable(R.drawable.next));
            }

            holder.tv_name.setText(groupInfo.get(groupPosition).getName());
            return view;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

            View view = convertView;
            ChildHolder holder = null;
            if (view == null) {
                holder = new ChildHolder();
                view = LayoutInflater.from(ActivityContacts.this).inflate(R.layout.child_phone_item, null);
                holder.tv_number = (TextView) view.findViewById(R.id.tv_number);
                view.setTag(holder);
            } else {
                holder = (ChildHolder) view.getTag();
            }


            holder.tv_number.setText(groupInfo.get(groupPosition).getContactsNumbers().get(childPosition));

            return view;

        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        class GroupHolder {
            public TextView tv_name;
            public ImageView arrow;
        }

        class ChildHolder {
            public TextView tv_number;
        }


    }

    public int linkManCount;
    int  pageCount = 20;
    List<ContactsPerson> contactsinfo;

    //获取所有联系人
    public void visitContacts() {
        contactsinfo = new ArrayList<>();
        Uri uri = Uri.parse("content://com.android.contacts/contacts");//所有联系人的工作路径
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(uri, new String[]{"_id"}, null, null, null);//获取所有联系人的ID
        ContactsPerson person;
        List<String> phonelist;
        while (cursor.moveToNext()) {
            int contactcId = cursor.getInt(0);
            person = new ContactsPerson();
            phonelist = new ArrayList<>();
            uri = Uri.parse("content://com.android.contacts/contacts/" + contactcId + "/data");//某一个联系人工作路径
            Cursor dateCursor = resolver.query(uri, new String[]{"mimetype", "data1", "data2"}, null, null, null);//获取某一个联系人的信息
            while (dateCursor.moveToNext()) {
                String date = dateCursor.getString(dateCursor.getColumnIndex("data1"));//信息
                String type = dateCursor.getString(dateCursor.getColumnIndex("mimetype"));//内容类型
                if ("vnd.android.cursor.item/name".equals(type)) {//name
                    person.setName(date);
                }
                if ("vnd.android.cursor.item/phone_v2".equals(type)) {//phone
                    phonelist.add(date);
                }
            }
            person.setContactsNumbers(phonelist);
            contactsinfo.add(person);
            dateCursor.close();
        }
        cursor.close();
        datas = contactsinfo;
        mList = new ContactsList();
        mList.setDatas(datas);
        save(mList);
        avi.hide();
        avi.setVisibility(View.GONE);
        mAdapter = new ExpandAdapter(contactsinfo);
        expand_contacts.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        expand_contacts.setVisibility(View.VISIBLE);
    }


    //保存数据
    public void save(ContactsList object){
        //创建字节输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out=null;
        try {
            //然后通过将字对象进行64转码，写入key值为key的sp中
            out = new ObjectOutputStream(baos);
            out.writeObject(object);
            String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
            SharedPreferences.Editor edit = sp.edit();
            edit.putString("contactslist", objectVal);
            edit.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if (out!=null) {
                    out.close();
                }
                if(baos!=null){
                    baos.close();
                }
            } catch (IOException e) {
            }

        }

    }

    //读取数据
    public void read(){
        if (sp.contains("contactslist")) {
            String objectVal = sp.getString("contactslist", null);
            byte[] buffer = Base64.decode(objectVal, Base64.DEFAULT);
            //一样通过读取字节流，创建字节流输入流，写入对象并作强制转换
            ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(bais);
                ContactsList list = (ContactsList) ois.readObject();
                datas = list.getDatas();
                mAdapter = new ExpandAdapter(list.getDatas());
                expand_contacts.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();
                avi.hide();
                avi.setVisibility(View.GONE);
                expand_contacts.setVisibility(View.VISIBLE);

            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (bais != null) {
                        bais.close();
                    }
                    if (ois != null) {
                        ois.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


